<?php
/**
 * @author Demianchuk Dmitro
 * @email d.demianchuk@gmail.com
 * @date 24.12.11
 * @version 1.0
 * @package adminArea.components.ATableEditor
 */
class TextInput extends EditorComponent
{
	/**
	 * @param CActiveRecord $model
	 * @return CActiveRecord
	 */
	public function save($model){
		if(isset($_POST['_formNull'][$this->name]) && $_POST['_formNull'][$this->name]=='on' && $this->allowNull()){
			$name = $this->name;
			$model->$name = '';
			return $model;
		}
		$name = $this->name;
		if($this->relationName===null){
			$model->$name = $_POST['_form'][$this->name];
		}elseif($this->relationName!==null && $this->relationField!==null){
			$relationName = $this->relationName;
			$relationField = $this->relationField;
			if($this->model->isNewRecord){
				$relations = $model->relations();
				$relationTable = $relations[$this->relationName][1];
				$model->$relationName = new $relationTable();
			}
			$model->$relationName->$relationField = $_POST['_form'][$this->name];
			$model->$relationName->save();
			$model->$name = $model->$relationName->id;
		}
		return $model;
	}

	/**
	 * @return string
	 */
	public function show(){
		$value = '';
		if($this->itemId!=0){
			$value = $this->getData($this->current,$this->relationName);
		}
		return '<input type="text" value="'.$value.'" name="_form['.$this->name.']" />';
	}

	/**
	 * @return boolean
	 */
	public function isNull(){
		if($this->allowNull()===true){
			$name = $this->name;
			if($this->current->$name===null){
				return true;
			}else{
				return false;
			}
		}else{
			return false;
		}
	}
}
